package com.soulkun.smarthome.ui.main.home.viewmodel

import androidx.lifecycle.*
import com.soulkun.smarthome.logic.creator.ApiServiceCreator
import com.soulkun.smarthome.logic.enum.ErrorCodeEnum
import com.soulkun.smarthome.logic.exception.ApiException
import com.soulkun.smarthome.logic.model.*
import com.soulkun.smarthome.logic.utils.ExceptionUtils
import com.soulkun.smarthome.logic.vo.WeatherVO
import kotlinx.coroutines.*
import soulkun.library.utils.logE
import soulkun.library.utils.toast
import kotlin.coroutines.coroutineContext

class AppMainHomeWeatherViewModel : ViewModel() {

    val showStatusLiveData = MutableLiveData<Boolean>(false)
    val weatherLiveData = MutableLiveData<WeatherVO>()

    fun getFamilyLocationWeather(latitude: Double, longitude: Double) =
        liveData(context = viewModelScope.coroutineContext + CoroutineExceptionHandler { _, throwable ->
            run {
                GlobalScope.launch(Dispatchers.Main){
                    "天气信息返回错误".toast()
                }
            }
        }) {
            coroutineScope {
                val job1 = viewModelScope.async(Dispatchers.IO) {
                    ApiServiceCreator.getWeatherRealtime(longitude, latitude)
                }
                val job2 = viewModelScope.async(Dispatchers.IO) {
                    ApiServiceCreator.getWeatherMinutely(longitude, latitude)
                }
                fun getWeatherVO(
                    weatherRealtimeModel: WeatherModel<WeatherRealtimeResultModel>,
                    weatherMinutelyModel: WeatherModel<WeatherMinutelyResultModel>
                ) = if (weatherRealtimeModel.status != "ok" || weatherMinutelyModel.status != "ok") {
                    val exception = ApiException(ErrorCodeEnum.UnknownError.code, "查询天气数据出错")
                    GlobalScope.launch(Dispatchers.Main) {
                        ExceptionUtils.catchException(exception)
                    }
                    Result.failure(exception)
                } else {
                    Result.success(
                        WeatherVO(
                            weatherRealtimeModel.result.realtime.temperature,
                            weatherRealtimeModel.result.realtime.humidity,
                            weatherRealtimeModel.result.realtime.skycon,
                            weatherRealtimeModel.result.realtime.airQuality,
                            weatherRealtimeModel.result.realtime.lifeIndex,
                            weatherMinutelyModel.result.minutely.description
                        )
                    )
                }
                emit(getWeatherVO(job1.await(), job2.await()))
            }
        }

}